package com.chris.cc.user.service.wrapper;

import com.chris.cc.user.model.vo.OnlineUserVO;
import com.chris.cc.user.model.vo.UserVO;
import com.chris.cc.user.service.OnlineUserService;
import com.chris.cc.user.service.UserService;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Copyright (c) 2018-2025, chris All rights reserved.
 * <p>
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * <p>
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * <p>
 * Author: haoka (haokang207@126.com)
 * <p>
 * Date: 2018/8/23 18:52<p>
 * 在线用户
 **/
@Service
public class OnlineUserServiceWrapper {

    @Autowired
    private OnlineUserService onlineUserService;
    @Autowired
    private UserService userService;


    /**
     * 查询
     *
     * @param page
     * @return
     */
    public Page<OnlineUserVO> query(@NonNull Pageable page) {
        List<String> keys = onlineUserService.queryAllKey();
        List<OnlineUserVO> list = new ArrayList<>();
        int total = keys.size();
        int offset = Long.valueOf(page.getOffset()).intValue();
        if (offset < total) {
            int size = (total - offset) < page.getPageSize() ? total - offset : page.getPageSize();
            List<String> subKeys = keys.subList(offset, size);
            subKeys.forEach(key -> {
                OnlineUserVO user = onlineUserService.get(key);
                user.setUser(UserVO.from(userService.getByTel(user.getTel())));
                list.add(user);
            });
        }
        return new PageImpl<>(list, page, total);
    }

    public void delete(String key) {
        onlineUserService.delete(key);
    }
}
